package app.sevenc.lib_framework.ktx

import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import app.sevenc.lib_framework.BaseFrameApplication
import app.sevenc.lib_framework.R
import java.lang.reflect.ParameterizedType


/**
 * 获取当前类绑定的泛型ViewModel-clazz
 *
 * @param obj Any
 * @param rawType Int
 * @return VM
 */
@Suppress("UNCHECKED_CAST")
fun <VM> getVmClazz(obj: Any,rawType:Int): VM {
    return (obj.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[rawType] as VM
}

/**
 * 在Activity中得到Application上下文的ViewModel
 *
 * @receiver AppCompatActivity
 * @return VM
 */
inline fun <reified VM : ViewModel> AppCompatActivity.getAppViewModel(): VM {
    (this.application as? BaseFrameApplication).let {
        if (it == null) {
            throw NullPointerException(getString(R.string.scframe_viewmodel_error))
        } else {
            return it.getAppViewModelProvider().get(VM::class.java)
        }
    }
}


/**
 * 在Fragment中得到Application上下文的ViewModel
 * 在fragment中调用该方法时，请在该Fragment onCreate以后调用或者请用by lazy方式懒加载初始化调用，
 * 不然会提示requireActivity没有导致错误
 *
 * @receiver Fragment
 * @return VM
 */
inline fun <reified VM : ViewModel> Fragment.getAppViewModel(): VM {
    (this.requireActivity().application as? BaseFrameApplication).let {
        if (it == null) {
            throw NullPointerException(getString(R.string.scframe_viewmodel_error))
        } else {
            return it.getAppViewModelProvider().get(VM::class.java)
        }
    }
}